package com.wisdytech.linkdcs.configuration.service.impl;

import com.alibaba.fastjson.JSON;
import com.wisdytech.common.enums.ConfigurationWebSocketType;
import com.wisdytech.linkdcs.configuration.dao.ITtEqConfigurationDao;
import com.wisdytech.linkdcs.configuration.dto.ConfigurationEqDto;
import com.wisdytech.linkdcs.configuration.dto.WebSocketDto;
import com.wisdytech.linkdcs.configuration.model.TtEqConfiguration;
import com.wisdytech.linkdcs.configuration.service.ITtEqConfigurationDataService;
import com.wisdytech.linkdcs.equipment.dto.EquipAlarmDataDto;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Transactional
public class TtEqConfigurationDataServiceImpl implements ITtEqConfigurationDataService {


    private static final Logger logger = LoggerFactory.getLogger(TtEqConfigurationDataServiceImpl.class);

    @Autowired
    ITtEqConfigurationDao ttEqConfigurationDao;

    /**
     * restful服务
     */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 主地址
     */
    @Value("${restful.baseUrl}")
    private String baseUrl;
    @Value("${restful.getEqRealData}")
    private String getEqRealData;


    @Override
    public List<ConfigurationEqDto> getConfigurationEqLists(String id) {
        TtEqConfiguration ttEqConfiguration = ttEqConfigurationDao.selectById(id);
        if (null == ttEqConfiguration) {
            return Collections.emptyList();
        }

        String jsonFile = ttEqConfiguration.getJsonEquips();

        if (StringUtils.isBlank(jsonFile)) {
            return Collections.emptyList();
        }

        //解析设备json
        try {
            return JSON.parseArray(jsonFile, ConfigurationEqDto.class);
        } catch (Exception e) {
            logger.error("解析组态设计json失败！！组态记录为" + ttEqConfiguration.getPkId() + "数据格式为" + jsonFile, e);
            return Collections.emptyList();
        }
    }


    @Override
    public void pushAlarmEquipmentData(List<EquipAlarmDataDto> alarmMsg, WebSocketSession session) {
        WebSocketDto dto = new WebSocketDto(
                ConfigurationWebSocketType.ALARM_DATA.getCode(), alarmMsg);
        TextMessage meg = new TextMessage(
                JSON.toJSONString(dto));
        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            //推送数据至终端
            if (session.isOpen()) {
                session.sendMessage(meg);
            }
        } catch (Exception e) {
            logger.error("推送websocket失败", e);
        } finally {
            lock.unlock();
        }


    }

    @Override
    public void pushEquipmentData(List<ConfigurationEqDto> eqDtos, WebSocketSession session) {

        WebSocketDto dto = new WebSocketDto(
                ConfigurationWebSocketType.EQUIP_DATA.getCode(), eqDtos);

        TextMessage meg = new TextMessage(
                JSON.toJSONString(dto));

        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            //推送数据至终端
            if (session.isOpen()) {
                session.sendMessage(meg);
            }
        } catch (Exception e) {
            logger.error("推送websocket失败", e);
        } finally {
            lock.unlock();
        }


    }

    @Override
    public void pushEquipmentData(List<ConfigurationEqDto> eqDtos, final Channel channel) {
        WebSocketDto dto = new WebSocketDto(ConfigurationWebSocketType.EQUIP_DATA.getCode(), eqDtos);
        TextWebSocketFrame msg = new TextWebSocketFrame(JSON.toJSONString(dto));
        if (channel.isActive()) {
            channel.writeAndFlush(msg);
        }
    }

    @Override
    public List<ConfigurationEqDto> getEquipmentRealData(String configurationId) {
        //获取组态信息
        List<ConfigurationEqDto> eqDtos = getConfigurationEqLists(configurationId);
        List<ConfigurationEqDto> eqDtoDatas = new ArrayList<>();

        //根据获取的设备和参数信息查询实时数据
        for (ConfigurationEqDto eqDto : eqDtos) {
            try {

                ConfigurationEqDto eqDtoData =
                        restTemplate.getForObject(baseUrl + getEqRealData + "?eqDto={eqDto}", ConfigurationEqDto.class, JSON.toJSONString(eqDto));

                eqDtoDatas.add(eqDtoData);

            } catch (Exception e) {
                logger.error("获取实时数据失败", e);
            }


        }

        return eqDtoDatas;
    }


}
